package com.adv.controller.base;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.adv.util.Constant;
import com.adv.util.MD5Util;
import com.adv.util.PropertiesUtil;

@Controller
public class UploadController extends BaseController {

	@ResponseBody
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Object upload(HttpServletRequest req) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
		MultipartFile file = mreq.getFile("file");
		if (null != file) {
			String fileName = file.getOriginalFilename();
			String downloadRoot = PropertiesUtil.get("downloadPrefix");
			String pathRoot = PropertiesUtil.get("uploadDir", "/tmp/upload/");
			String md5FileName = MD5Util.getMD5String(System.nanoTime() + "_" + fileName) + fileName.substring(fileName.lastIndexOf("."));
			System.out.println("文件保存地址：" + pathRoot + md5FileName);
			try {
				FileUtils.copyInputStreamToFile(file.getInputStream(), new File(pathRoot + md5FileName));
				resultMap.put(Constant.RESULTMSG, downloadRoot + md5FileName);
				resultMap.put(Constant.RESULTKEY, Constant.SUCCESS);
			} catch (Exception e) {
				logger.error("upload error: " + e.getMessage());
				resultMap.put(Constant.RESULTKEY, Constant.FAILURE);
			}
		} else {
			logger.error("upload error: no file");
			resultMap.put(Constant.RESULTKEY, Constant.UPLOAD_NO_FILE);
		}
		return resultMap;
	}

}
